/**
 * 系统基础框架，用户登录
 * @author 马登军
 */
package cn.lvxs.freeeast.base_System.action;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import cn.lvxs.framework.Application;
import cn.lvxs.framework.SystemConfig;

import com.opensymphony.xwork2.ActionSupport;
import com.wabacus.config.Config;
import com.wabacus.config.ConfigLoadManager;
import com.wabacus.system.ReportRequest;
import com.wabacus.util.DesEncryptTools;

public class Login extends ActionSupport {

	private static final long serialVersionUID = -3534547068127577926L;
	private String username;//用户名
	private String password;//密码
	
    public String execute() throws Exception {
    	HttpSession session = ServletActionContext.getRequest().getSession();
    	if(isInvalid(username) && isInvalid(password)){
    		session.invalidate();
        	return INPUT;
        }
    	else if (isInvalid(username)){
        	this.addActionError("用户名错误！");
        	return INPUT;
        }else if (isInvalid(password)){
        	this.addActionError("密码错误！");
        	return INPUT;
        }
        
    	SystemConfig sysConfig = new SystemConfig();
    	if(Application.get("sysConfig")!=null){
    		sysConfig=(SystemConfig)Application.get("sysConfig");
    	}
		long UserState=0,LoginState=1,UserID=0;
		String pwdTemp=password;
    	try {
    		if(ConfigLoadManager.currentDynClassLoader!=null){
    			Connection conn = Config.getInstance().getDataSource("").getConnection();
				PreparedStatement stmt = null;
				Calendar cal = Calendar.getInstance();
				//从数据库中取得用户信息，进行判断
				try {
					stmt = conn.prepareStatement("select * from UserInfo where Username=? and (Password=? or Password=?) order by state desc,id");
					stmt.setString(1, username);//用户名
					String PasswordTemp=DesEncryptTools.encrypt(password);//加密的密码
					stmt.setString(2, PasswordTemp);
					stmt.setString(3, password);//没有加密码
					
					ResultSet rs = stmt.executeQuery();
					if (rs.next()) {
						UserState=rs.getLong("State");
						if(UserState<=0){
				        	this.addActionError("用户已经锁定，请联系管理员！");
				        	LoginState=0;
				        }
						if(rs.getDate("LoginTime")!=null){
							cal.setTime(rs.getDate("LoginTime"));
							cal.add(Calendar.DATE, (int)sysConfig.getAutolockdays());
							if(cal.getTime().before(new Date())){
					        	this.addActionError("您的帐号已经超过"+sysConfig.getAutolockdays()+"天没有登录系统了，帐号已被锁定不能登录，请联系管理员！");
					        	LoginState=0;
					        	UserState=0;
							}
						}
						if(rs.getDate("ChangePasswordDate")!=null){
							cal.setTime(rs.getDate("ChangePasswordDate"));
							cal.add(Calendar.DATE, (int)sysConfig.getValiddays());
							if(cal.getTime().before(new Date())){
					        	this.addActionError("您的密码已经过期，请联系管理员！");
					        	LoginState=0;
					        	UserState=0;
							}
						}
						if(UserState>0){
							UserID=rs.getLong("ID");
							session.setAttribute("UserID", UserID);
							session.setAttribute("UserName", rs.getString("RealName"));
							pwdTemp=rs.getString("Password");
							LoginState=1;
						}
					}
					else{
			        	this.addActionError("用户名或密码错误，登录失败！");
			        	LoginState=-1;
					}
					rs.close();
					if(UserState>0){
						if(pwdTemp.equals(password)){
							if (stmt != null) {
								stmt.close();
							}
							stmt = conn.prepareStatement("Update UserInfo set LoginTime=?,SessionIDs=?,Password=? where ID=?");
							stmt.setDate(1, new java.sql.Date(System.currentTimeMillis()));//登陆时间
							stmt.setString(2, session.getId());//登录回话ID
							stmt.setString(3, DesEncryptTools.encrypt(pwdTemp));//登录回话ID
							stmt.setLong(4, UserID);//用户ID
							stmt.executeUpdate();
						}
						else{
							if (stmt != null) {
								stmt.close();
							}
							stmt = conn.prepareStatement("Update UserInfo set LoginTime=?,SessionIDs=? where ID=?");
							stmt.setDate(1, new java.sql.Date(System.currentTimeMillis()));//登陆时间
							stmt.setString(2, session.getId());//登录回话ID
							stmt.setLong(3, UserID);//用户ID
							stmt.executeUpdate();
						}
					}
					else{
						if (stmt != null) {
							stmt.close();
						}
						stmt = conn.prepareStatement("Update UserInfo set State=? where ID=?");
						stmt.setLong(1, UserState);//用户状态
						stmt.setLong(2, UserID);//用户ID
						stmt.executeUpdate();
					}
				} catch (SQLException e) {
				} finally {
					try {
						if (stmt != null) {
							stmt.close();
						}
					} catch (SQLException e) {
					}
					try {
						if (conn != null) {
							conn.close();
						}
					} catch (SQLException e) {
					}
				}
    		}
		} catch (Exception e) {
		}
    	if(UserState>0 && LoginState>0 && UserID>0){
    		return SUCCESS;
    	}
    	else{
    		return INPUT;
    	}
    }	
    public String resetAdminPassword() throws Exception {
    	if(username==null || username.isEmpty()){
    		username="admin";
    	}
    	username=username.toLowerCase();
    	try {
    		if(ConfigLoadManager.currentDynClassLoader!=null){
    	    	SystemConfig sysConfig = new SystemConfig();
    	    	if(Application.get("sysConfig")!=null){
    	    		sysConfig=(SystemConfig)Application.get("sysConfig");
    	    	}
    	    	Connection conn = Config.getInstance().getDataSource("").getConnection();
				PreparedStatement stmt = null;
				Calendar cal = Calendar.getInstance();
				//从数据库中取得用户信息，进行判断
				try {
					stmt = conn.prepareStatement("Update UserInfo set ChangePasswordDate=?,Password=? where LCASE(Username)=?");
					stmt.setDate(1, new java.sql.Date(System.currentTimeMillis()));//修改密码时间
					stmt.setString(2, sysConfig.getInitpassword());//密码
					stmt.setString(3, username);//用户名
					stmt.executeUpdate();
					this.addActionMessage("“" + username +"”用户密码重置成功！");
				} catch (SQLException e) {
				} finally {
					try {
						if (stmt != null) {
							stmt.close();
						}
					} catch (SQLException e) {
					}
					try {
						if (conn != null) {
							conn.close();
						}
					} catch (SQLException e) {
					}
				}
    		}
		} catch (Exception e) {
		}
    	return INPUT;
    }

    private boolean isInvalid(String value) {
        return (value == null || value.length() == 0);
    }

	/**
	 * @return the username
	 */
	public synchronized final String getUsername() {
		return username;
	}

	/**
	 * @param username the username to set
	 */
	public synchronized final void setUsername(String username) {
		this.username = username;
	}

	/**
	 * @return the password
	 */
	public synchronized final String getPassword() {
		return password;
	}

	/**
	 * @param password the password to set
	 */
	public synchronized final void setPassword(String password) {
		this.password = password;
	}
    
    
}
